package com.douyang.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyang.base.client.UserClient;
import com.douyang.base.model.Result;
import com.douyang.base.model.UserBaseInfo;
import com.douyang.base.utils.UserUtil;

import com.douyang.dto.GetVideoListByLikesDTO;
import com.douyang.dto.VideoInfoListDTO;
import com.douyang.base.expcetion.VideoException;
import com.douyang.mapper.ReviewVideoInfoMapper;
import com.douyang.mapper.VideoBaseInfoMapper;
import com.douyang.base.model.PageResult;
import com.douyang.pojo.VideoBaseInfo;
import com.douyang.pojo.VideoInfo;
import com.douyang.service.VideoBaseInfoService;
import com.douyang.service.VideoInfoService;
import com.douyang.utils.ESUtils;
import com.douyang.utils.MinioUtil;
import com.douyang.vo.VideoBaseInfoListVO;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoma
 * @since 2025-02-27
 */
@Service
public class VideoBaseInfoServiceImpl extends ServiceImpl<VideoBaseInfoMapper, VideoBaseInfo> implements VideoBaseInfoService {

    @Autowired
    VideoInfoService videoInfoService;

    @Autowired
    ReviewVideoInfoMapper reviewVideoInfoMapper;

    @Autowired
    MinioUtil minioUtil;

    @Autowired
    UserClient userClient;

    @Autowired
    ESUtils esUtils;

    @Override
    public PageResult<VideoBaseInfoListVO> getVideoInfoList(VideoInfoListDTO videoInfoListDTO) {
        Boolean showDeleted=false;
        if(videoInfoListDTO.getAuthorId()!=null && videoInfoListDTO.getAuthorId()==-1){//-1:自己的全部作品
            videoInfoListDTO.setAuthorId(UserUtil.getLoginUserBaseInfo().getId());
            showDeleted=true;
        }else if(videoInfoListDTO.getAuthorId()!=null && videoInfoListDTO.getAuthorId()==-2){ //-2自己的未下架的作品
            videoInfoListDTO.setAuthorId(UserUtil.getLoginUserBaseInfo().getId());
        }
        Page<VideoBaseInfo> page;
//        Page<VideoBaseInfo> page = videoInfoListDTO.getPage();
//        page=lambdaQuery()
//                .like(StringUtils.isNotEmpty(videoInfoListDTO.getTitle()),VideoBaseInfo::getTitle,videoInfoListDTO.getTitle())
//                .eq(StringUtils.isNotEmpty(videoInfoListDTO.getType()),VideoBaseInfo::getTypeName,videoInfoListDTO.getType())
//                .eq(videoInfoListDTO.getAuthorId()!=null,VideoBaseInfo::getAuthorId,videoInfoListDTO.getAuthorId())
//                .eq(!showDeleted,VideoBaseInfo::getDeleted,false)
//                .orderByDesc(VideoBaseInfo::getCreateTime)
//                .page(page);
        try {
            page=esUtils.selectByVideoInfoDTO(videoInfoListDTO,showDeleted);
        }catch (Exception e){
            throw new VideoException(e.getMessage());
        }


        return getVideoBaseInfoListVOPageResult(page);
    }

    @Override
    public String uploadImage(MultipartFile file) {
        try {
            return minioUtil.uploadImage(file, DigestUtils.md5DigestAsHex(file.getInputStream()));
        }catch (Exception e){
            throw new VideoException(e.getMessage());
        }
    }

    @Override
    @Transactional
    public void removeVideo(Long id,Boolean deleted) {
        VideoBaseInfo videoBaseInfo = getById(id);
        UserBaseInfo loginUserBaseInfo = UserUtil.getLoginUserBaseInfo();
        if(!videoBaseInfo.getAuthorId().equals(loginUserBaseInfo.getId())){
            throw new VideoException("无权下架");
        }
        videoBaseInfo.setDeleted(deleted);
        updateById(videoBaseInfo);
        try {
            esUtils.updateVideoBase(videoBaseInfo);
        }catch (Exception e){
            throw new VideoException(e.getMessage());
        }

    }

    @Override
    public PageResult<VideoBaseInfoListVO> getVideoInfoListByLikes(GetVideoListByLikesDTO getVideoListByLikesDTO) {
        if(getVideoListByLikesDTO.getUserId()==null){
            getVideoListByLikesDTO.setUserId(UserUtil.getLoginUserBaseInfo().getId());
        }
        Result<List<Long>> userLikedVideoIdsResult = userClient.getUserLikedVideoIds(getVideoListByLikesDTO.getUserId());
        if(userLikedVideoIdsResult.getCode()!=200)throw new VideoException("getVideoInfoListByLikes:"+userLikedVideoIdsResult.getMsg());
        List<Long> userLikedVideoIds = userLikedVideoIdsResult.getData();
        if(CollectionUtils.isEmpty(userLikedVideoIds))return new PageResult<>(List.of(),1,1,getVideoListByLikesDTO.getPageSize());
        Page<VideoBaseInfo> page = lambdaQuery()
                .in(VideoBaseInfo::getId, userLikedVideoIds)
                .page(getVideoListByLikesDTO.getPage());

        return getVideoBaseInfoListVOPageResult(page);
    }

    @NotNull
    private PageResult<VideoBaseInfoListVO> getVideoBaseInfoListVOPageResult(Page<VideoBaseInfo> page) {
        return PageResult.of(page,videoBaseInfo -> {
            VideoBaseInfoListVO videoBaseInfoListVO=new VideoBaseInfoListVO();
            BeanUtils.copyProperties(videoBaseInfo,videoBaseInfoListVO);
            VideoInfo videoInfo = videoInfoService.lambdaQuery().eq(VideoInfo::getVideoId, videoBaseInfo.getId()).one();
            BeanUtils.copyProperties(videoInfo,videoBaseInfoListVO);
            Result<Integer> videoLikeCount = userClient.getVideoLikeCount(videoBaseInfo.getId());
            videoBaseInfoListVO.setLikedCount(videoLikeCount.getCode()==200?videoLikeCount.getData():0);
            return videoBaseInfoListVO;
        });
    }


}
